<template>
    <div id="mapContainer" class="mapContainer"></div>
</template>

<script lang="ts" setup>
import { Feature, Map, Overlay, View } from 'ol';
import { Point } from 'ol/geom';
import { Vector as VectorLayer } from 'ol/layer';
import TileLayer from 'ol/layer/Tile';
import { Vector as VectorSource, XYZ } from 'ol/source';
import { Icon, Style } from 'ol/style';
import { onMounted, ref } from 'vue';
import icon1 from '@/assets/icon1.png';
import { Draw } from 'ol/interaction';

const map = ref();

const initMap = () => {
    map.value = new Map({
        target: 'mapContainer'
    });

    const layer = new TileLayer({
        source: new XYZ({
            url: `http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7`
        })
    });

    map.value.addLayer(layer);

    const view = new View({
        center: [116.397477, 39.908692],
        zoom: 10,
        projection: 'EPSG:4326'
    });
    map.value.setView(view);

    map.value.on('click', (e: any) => {
        console.log('point=', e, e.target.viewport_);
        // if(e.target.viewport_)
        addOverlay(e.coordinate);
    });

    setMarker();
};

onMounted(() => {
    initMap();
});

const addOverlay = (point: number[]) => {
    let feature = new Feature({
        geometry: new Point(point)
    });

    const source = new VectorSource({
        features: [feature]
    });
    const layer = new VectorLayer({
        source: source,
        style: new Style({
            image: new Icon({
                anchor: [0.5, 1],
                src: icon1,
                size: [32, 32]
            })
        })
    });
    map.value.addLayer(layer);

    const draw = new Draw({
        source: source,
        type: 'Point'
    });

    draw.on('drawend', (e) => {
        console.log('drawend=', e);
        // 如果只需要放置一个的话可以移除该交互，否则可以一直添加
        map.value.removeInteraction(draw);
    });

    map.value.addInteraction(draw);
};

const setMarker = () => {
    let point = [116.34625651238589, 39.82340405788433];
    const feature = new Feature({
        geometry: new Point(point)
    });
    const source = new VectorSource({
        features: [feature]
    });
    const layer = new VectorLayer({
        source: source,
        style: new Style({
            image: new Icon({
                anchor: [0, 0],
                size: [100, 100],
                src: icon1
            })
        })
    });
    map.value.addLayer(layer);

    let el = document.createElement('div');
    el.innerHTML = '<div>新发地</div>';

    let overlay = new Overlay({
        element: el,
        position: point,
        offset: [-10, -20],
        autoPan: true
    });
    map.value.addOverlay(overlay);
};
</script>

<style lang="scss" scoped>
.mapContainer {
    width: 100%;
    height: 100%;
}
</style>